//
//  FPMeProfileController.m
//  FinanceProject
//
//  Created by 陈显摆 on 2025/3/12.
//

#import "FPMeProfileController.h"
#import "FPAuthenticationFooterView.h"
#import "FPMeProfileModel.h"
#import "FPMeProfileCell.h"
#import "FPAddressPopupView.h"
#import "FPNoDataController.h"
#import "FPMeProfileTwoController.h"
#import "FPBankCardModel.h"
#import "FPMeProfileStepView.h"

@interface FPMeProfileController () <UITableViewDelegate , UITableViewDataSource , HJCActionSheetDelegate , UITextFieldDelegate , UIGestureRecognizerDelegate>

@property (nonatomic , strong) FPAuthenticationFooterView *footerView;
@property (nonatomic , strong) NSDictionary *addressSource;
@property (nonatomic , strong) FPAddressPopupView *addressPicker;
@property (nonatomic , strong) NSString *liveLocation; //!< 居住所在地 地图选择器结果
@property (nonatomic , strong) NSIndexPath *ip;
@property (nonatomic , strong) NSMutableDictionary *params;
@property (nonatomic , strong) FPMeModelProfile *tempModel;
@property (nonatomic , strong) NSString *cityCode;
@property (nonatomic , strong) FPMeProfileStepView *stepView;

@end

@implementation FPMeProfileController

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];

    // 只有当前控制器在导航栈顶才设置手势代理
    if (self.navigationController.viewControllers.lastObject == self) {
        self.navigationController.interactivePopGestureRecognizer.delegate = (id<UIGestureRecognizerDelegate>)self;
        self.navigationController.interactivePopGestureRecognizer.enabled = YES;
    }
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];

    // 离开页面前恢复手势代理（防止影响其他页面）
    if (self.navigationController.interactivePopGestureRecognizer.delegate == (id<UIGestureRecognizerDelegate>)self) {
        self.navigationController.interactivePopGestureRecognizer.delegate = nil;
    }
}


- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer {
    
    [self detainmentPopupAction];
    
    return NO;
}

- (void)backAction {
    
    [self detainmentPopupAction];
}

- (void)detainmentPopupAction {
    
    LXAlertView *alert = [[LXAlertView alloc] initDetainmentWithTitleString:@"您要放弃借款吗" contentString:@"当前完成后仅需最后一步即可申请借款" btn1:@"去意已决" btn2:@"我再想想" alertAlertResult:^(NSInteger index) {
        
        if (index == 2) {
            
            [self.navigationController popViewControllerAnimated:YES];
        }
    }];
    [alert showLXAlertView];
}

- (NSMutableDictionary *)params {
    
    if (!_params) {
        
        _params = NSMutableDictionary.dictionary;
    }
    return _params;
}

- (NSDictionary *)loadAddressDataFromFile {
    
//    NSString *path = [[NSBundle mainBundle] pathForResource:@"Address" ofType:@"plist"];
//    
//    NSDictionary *rootDict = [NSDictionary dictionaryWithContentsOfFile:path];
    
    NSDictionary *rootDict = [FPBankCardModel readJSONFileWithName:@"Address"];
    
    return rootDict;
}

- (FPAddressPopupView *)addressPicker {
    
    if (!_addressPicker) {
        
        _addressPicker = [[FPAddressPopupView alloc] initWithAddressData:self.addressSource];
        [self.view addSubview:_addressPicker];
    }
    return _addressPicker;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationController.interactivePopGestureRecognizer.delegate = self;
    
    if (self.province.length > 0) {
        
        self.liveLocation = [NSString stringWithFormat:@"%@%@",self.province,self.cityName];
    }
    
    // 删除控制器
    NSMutableArray *marr = [[NSMutableArray alloc] initWithArray:self.navigationController.viewControllers];
    
    for (UIViewController *vc in marr) {
    
        if ([vc isKindOfClass:NSClassFromString(@"FPAuthenticationController")]) {
            
            [marr removeObject:vc];
            break;
        }
    }
    
    self.navigationController.viewControllers = marr;
}

- (void)initUI {
    
    [self setTitle:@"我的资料" style:(XYCustomNavigationStyleWhite) hiddenBackBtn:NO];
    self.view.backgroundColor = [UIColor hexColor:@"#F4F6FA"];
    
    CGFloat h = 12.f + 33.f + 80.f;
    
    UIView *v = [[UIView alloc] initWithFrame:CGRectMake(0.f, UIDevice.navigationFullHeight, SCREEN_WIDTH, h)];
    
    v.backgroundColor = UIColor.clearColor;
    
    UIView *headView = [[UIView alloc] initWithFrame:CGRectMake(16.f, 12.f, SCREEN_WIDTH - 32.f, 33.f)];
    headView.backgroundColor = [[UIColor hexColor:@"#0D6FFF"]colorWithAlphaComponent:.05f];
    headView.clipsToBounds = YES;
    headView.layer.cornerRadius = 8.f;
    [v addSubview:headView];
    
    UIImageView *iv = [[UIImageView alloc] initWithFrame:CGRectMake(12.f, 33.f / 2.f - 8.f, 16.f, 16.f)];
    [headView addSubview:iv];
    iv.image = IMG(@"icon_authentic_head");
    
    UILabel *lab = [[UILabel alloc] initWithFrame:CGRectMake(iv.right + 4.f, 0.f, SCREEN_WIDTH - iv.right - iv.left - 32.f, 33.f)];
    [headView addSubview:lab];
    lab.font = FONT(12.f);
    lab.textColor = [UIColor hexColor:@"#6A6A6A"];
    lab.text = @"国家级数据加密保护，仅用于贷款审核。";
    
    self.stepView = [[NSBundle mainBundle] loadNibNamed:NSStringFromClass(FPMeProfileStepView.class) owner:nil options:nil].lastObject;
    [v addSubview:self.stepView];
    self.stepView.frame = CGRectMake(0.f, headView.bottom + 12.f, SCREEN_WIDTH, 80.f);
    [self.stepView setStep:1];
    
    [self.view addSubview:v];
    
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.view addSubview:self.tableView];
    self.tableView.backgroundColor = UIColor.clearColor;//[UIColor colorWithHexString:@"#F4F6FA"];
    self.tableView.frame = CGRectMake(0.f, UIDevice.navigationFullHeight + v.height, SCREEN_WIDTH, SCREEN_HEIGHT - UIDevice.navigationFullHeight - v.height - 71.f - UIDevice.safeDistanceBottom);
    
    self.footerView = [[NSBundle mainBundle] loadNibNamed:NSStringFromClass(FPAuthenticationFooterView.class) owner:nil options:nil].lastObject;
    [self.view addSubview:self.footerView];
    self.footerView.frame = CGRectMake(0.f, SCREEN_HEIGHT - UIDevice.safeDistanceBottom - 71.f, SCREEN_WIDTH, 71.f);
    self.footerView.selectImgView.hidden = YES;
    self.footerView.privacyLab.hidden = YES;
    
    [self.footerView.nextBtn setTitle:@"下一步" forState:(UIControlStateNormal)];
    
    self.footerView.topHeight.constant = -17.67f; //
    self.footerView.backgroundColor = [UIColor hexColor:@"#F4F6FA"];
    
    UIView *bottomV = [[UIView alloc] initWithFrame:CGRectMake(0.f, SCREEN_HEIGHT - UIDevice.safeDistanceBottom, SCREEN_WIDTH, UIDevice.safeDistanceBottom)];
    [self.view addSubview:bottomV];
    bottomV.backgroundColor = [UIColor hexColor:@"#F4F6FA"];
    
    [self getUserInfo];
    
#warning handle
    [self.footerView.nextBtn handleViewControlEvents:UIControlEventTouchUpInside withBlock:^{
        
        if ([self completeProfiles]) {
            
            [self submitAction];
        }
    }];
}

- (void)getUserInfo {
    
    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"UserProfileConfig" ofType:@"json"];
    NSData *jsonData = [NSData dataWithContentsOfFile:filePath];
    
    NSError *error;
    NSArray *list = [FPMeProfileModel arrayOfModelsFromData:jsonData error:&error];
    
    [self.dataSource removeAllObjects];
    
    for (FPMeProfileModel *m in list) {
        
        [self.dataSource addObject:m];
    }
    
    [self.dataSource removeLastObject];
    [self.dataSource removeLastObject];
    [self.dataSource removeLastObject];
    [self.dataSource removeLastObject];
}

- (void)loadUserInfoOnService {
    
    [FPUserInfoModel getUserInfoWithSuccess:^(FPUserInfoModel * _Nonnull model) {
        
        NSDictionary *modelDic = [model toDictionary];
        
        NSDictionary *dic = [model getAllPropertiesWithTypes];
        
        NSMutableArray *temp = NSMutableArray.array;
        
        for (NSString *str in dic.allKeys) {
            
            if ([[dic objectForKey:str] hasPrefix:@"T@\"NSString\""]) {
                
                [temp addObject:str];
            }
        }
        
        for (FPMeProfileModel *m in self.dataSource) {
            
            for (NSUInteger i = 0; i < m.profile.count; i ++) {
                
                FPMeModelProfile *pf = m.profile[i];
                
                if ([temp containsObject:pf.param_key]) {
                    
                    // 输入框
                    if ([pf.type isEqualToString:@"input"]) {
                     
                        pf.value = [modelDic objectForKey:pf.param_key];
                    }
                    // 选择 sheet
                    else if ([pf.type isEqualToString:@"select"]) {
                        
                        if (![NSString isBlankString:[modelDic objectForKey:pf.param_key]]) {
                         
                            pf.select_content_index = [[modelDic objectForKey:pf.param_key] integerValue];
                        }
                        else {
                            
                            pf.select_content_index = -1;
                        }
                    }
                    // 地址选择器
                    else if ([pf.type isEqualToString:@"select_location"]) {
                        
                        pf.value = [modelDic objectForKey:pf.param_key];
                        self.cityCode = pf.value;
                    }
                }
            }
        }
        
        
        [self.tableView reloadData];
        
    } failure:^(NSError * _Nonnull error) {
        [self.tableView reloadData];
    }];
}

//// 获取所有属性名 和 类型
//- (NSDictionary<NSString *, NSString *> *)getAllPropertiesWithTypes:(FPUserInfoModel *)model {
//    unsigned int count;
//    objc_property_t *properties = class_copyPropertyList([model class], &count);
//    
//    NSMutableDictionary *propertyInfo = [NSMutableDictionary dictionary];
//    for (unsigned int i = 0; i < count; i++) {
//        const char *propertyName = property_getName(properties[i]);
//        const char *attributes = property_getAttributes(properties[i]);
//        [propertyInfo setObject:[NSString stringWithUTF8String:attributes] forKey:[NSString stringWithUTF8String:propertyName]];
//    }
//    
//    free(properties);
//    return propertyInfo;
//}

//printPropertiesWithTypes([FPUserLoanInfo class]);






- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return self.dataSource.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    FPMeProfileModel *model = self.dataSource[section];
    
    return model.profile.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    
    return 50.f;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    FPMeProfileModel *model = self.dataSource[section];
    
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0.f, 0.f, SCREEN_WIDTH, 50.f)];
    view.backgroundColor = UIColor.whiteColor;
    
    UILabel *lab = [[UILabel alloc] initWithFrame:CGRectMake(16.f + 12.f, 12.f, 200.f, 26.f)];
    lab.font = [UIFont systemFontOfSize:16.f weight:(UIFontWeightSemibold)];
    lab.textColor = [UIColor hexColor:@"#3A3A3A"];
    [view addSubview:lab];
    
    if (!model.isOptional) {
        
        NSString *text = [NSString stringWithFormat:@"* %@",model.title];
        NSMutableAttributedString *attStr = [[NSMutableAttributedString alloc] initWithString:text];
        NSRange range = [text rangeOfString:@"* "];
        [NSString stringToAttribute:attStr color:UIColor.redColor range:range];
        lab.attributedText = attStr;
    }
    else {
     
        lab.text = model.title;
    }
    
    [UIView setCornerForView:view withRadius:8.f bounds:CGRectMake(16.f, 0.f, SCREEN_WIDTH - 32.f, 50.f) corners:(UIRectCornerTopLeft | UIRectCornerTopRight)];
    
    return view;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    FPMeProfileCell *cell;
    
    if (!cell) {
    
        cell = [[NSBundle mainBundle] loadNibNamed:NSStringFromClass(FPMeProfileCell.class) owner:nil options:nil].lastObject;
    }
    
    FPMeProfileModel *model = self.dataSource[indexPath.section];
    
    FPMeModelProfile *profile = model.profile[indexPath.row];
    
    if (indexPath.row == model.profile.count - 1) {
        
        [UIView setCornerForView:cell.backView withRadius:8.f bounds:CGRectMake(0.f, 0.f, SCREEN_WIDTH - 32.f, 50.f) corners:(UIRectCornerBottomLeft | UIRectCornerBottomRight)];
    }
    
    if ([profile.type isEqualToString:@"select"] || [profile.type isEqualToString:@"select_location"]) {
        
        cell.imgView.image = IMG(@"icon_setting_arrow_right");
        cell.textField.placeholder = @"请选择";
        cell.textField.userInteractionEnabled = NO;
    }
    else if ([profile.type isEqualToString:@"input"]) {
        
        cell.textField.placeholder = @"请输入";
        cell.textField.userInteractionEnabled = YES;
        cell.imgView.hidden = YES;
    }
    
    if ([profile.keyborad isEqualToString:@"number"]) {
        
        cell.textField.keyboardType = UIKeyboardTypeNumberPad;
    }
    
    if ([profile.title isEqualToString:@"居住地"]) { // type: select_location
        
        if (self.liveLocation) {
            
            profile.value = self.liveLocation;
        }
    }
    
    if ([profile.type isEqualToString:@"select"]) {
        
    }
    // input 和 select_location
    else {
        
        cell.textField.text = profile.value.length > 0 ? profile.value : @"";
    }
    
    if (profile.content.count > 0) {
        
        if (profile.select_content_index >= 0) {
            
            FPMeModelContent *ctt = profile.content[profile.select_content_index];
            cell.textField.text = ctt.value;
        }
    }
    
    cell.textField.indexPath = indexPath;
    cell.textField.delegate = self;
    
    if (!profile.isOptional) {
        
        NSString *text = [NSString stringWithFormat:@"*%@",profile.title];
        NSMutableAttributedString *attStr = [[NSMutableAttributedString alloc] initWithString:text];
        NSRange range = [text rangeOfString:@"*"];
        [NSString stringToAttribute:attStr color:UIColor.redColor range:range];
        cell.titleLab.attributedText = attStr;
    }
    else {
     
        cell.titleLab.text = profile.title;
    }
    
    return cell;
}

#pragma mark - 输入监听
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {

    if ([string isEqualToString:@""]) {
        
        return YES;
    }
    
    FPCustomTextField *tf = (FPCustomTextField *)textField;
    
    FPMeProfileModel *model = self.dataSource[tf.indexPath.section];
    
    FPMeModelProfile *profile = model.profile[tf.indexPath.row];
    
    // 年龄
    if ([profile.title isEqualToString:@"年龄"]) {
        
        return textField.text.length < 2;
    }
    
    profile.value = textField.text;
    
    return textField.text.length < 30;
}

- (void)textFieldDidEndEditing:(UITextField *)textField {
    
    FPCustomTextField *tf = (FPCustomTextField *)textField;
    
    FPMeProfileModel *model = self.dataSource[tf.indexPath.section];
    
    FPMeModelProfile *profile = model.profile[tf.indexPath.row];
    
    profile.value = textField.text;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    [self.view endEditing:YES];
    
    FPMeProfileModel *model = self.dataSource[indexPath.section];
    
    FPMeModelProfile *profile = model.profile[indexPath.row];
    
    if ([profile.title isEqualToString:@"居住地"]) {
        
        [self selectAddressAction];
    }
    else {
        
        NSMutableArray *source = NSMutableArray.array;
        
        for (FPMeModelContent *content in profile.content) {
            
            [source addObject:content.value];
        }
        
        if ([profile.type isEqualToString:@"select"]) {
            
            self.ip = indexPath;
            HJCActionSheet *sheet = [[HJCActionSheet alloc] initWithDelegate:self CancelTitle:@"取消" OtherTitlesArray:source];
            [sheet show];
        }
    }
}

- (void)actionSheet:(HJCActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
    
    FPMeProfileModel *model = self.dataSource[self.ip.section];
    
    FPMeModelProfile *profile = model.profile[self.ip.row];
    
//    FPMeModelContent *content = profile.content[buttonIndex - 1];
    
    profile.select_content_index = buttonIndex - 1;
    
    
    if ([profile.title isEqualToString:@"职业类型"]) {
        
        if (profile.select_content_index == 0 || profile.select_content_index == 1) {
            
            if (model.profile.count < 3) {
             
                [model.profile insertObject:self.tempModel atIndex:1];
            }
        }
        else {
            
            [model.profile removeObject:self.tempModel];
        }
    }
    
    
    [self.tableView reloadData];
}


#pragma mark - 地址选择
- (void)selectAddressAction {
    
    [self.view endEditing:YES];
    
    self.addressSource = [self loadAddressDataFromFile];
    
    [self.addressPicker show];  // 显示选择器视图
    
    WeakSelf;
    self.addressPicker.selectionBlock = ^(NSString *province, NSString *city , NSString *cityCode) {
        
        weakSelf.cityCode = cityCode;
        
        if ([province isEqualToString:city]) {
            
            NSString *str = [NSString stringWithFormat:@"%@",province];
            
            weakSelf.liveLocation = str;
        }
        else {
            
            NSString *str = [NSString stringWithFormat:@"%@%@",province, city];
            
            weakSelf.liveLocation = str;
        }
        
        [weakSelf.tableView reloadData];
        
        [weakSelf.addressPicker dismiss];
    };
}

- (BOOL)completeProfiles {
    
    NSMutableDictionary *params = NSMutableDictionary.dictionary;
    
    for (NSUInteger i = 0; i < self.dataSource.count; i ++) {
        
        FPMeProfileModel *model = self.dataSource[i];
        
        for (NSUInteger j = 0; j < model.profile.count; j ++) {
    
            FPMeModelProfile *profile = model.profile[j];
            
            // 必填项
            if (!profile.isOptional) {
             
                if ([profile.type isEqualToString:@"select"]) {
                    
                    if (profile.select_content_index == -1) {
                        
                        FeedBackGeneratorAction;
                        [self showText:[NSString stringWithFormat:@"请选择%@", profile.title]];
                        return NO;
                    }
                    else {
                        
                        [params setObject:@(profile.select_content_index) forKey:profile.param_key];
                    }
                }
                else if ([profile.type isEqualToString:@"select_location"]) {
                    
                    if (self.cityCode.length > 0) {
                        
                        [params setObject:self.cityCode forKey:profile.param_key];
                        [params setValue:self.cityID forKey:@"local"];
                    }
                    else {
                        
                        if (self.province.length > 0) {
                            
                            [params setObject:self.cityID forKey:profile.param_key];
                        }
                        else {
                         
                            FeedBackGeneratorAction;
                            [self showText:[NSString stringWithFormat:@"请选择%@", profile.title]];
                            return NO;
                        }
                    }
                }
                else if ([profile.type isEqualToString:@"input"]) {
                    
                    if (profile.value.length > 0) {
                        
                        [params setObject:profile.value forKey:profile.param_key];
                    }
                    else {
                        
                        FeedBackGeneratorAction;
                        [self showText:[NSString stringWithFormat:@"请输入%@", profile.title]];
                        return NO;
                    }
                }
            }
            // 不是必填
            else {
                
                if ([profile.type isEqualToString:@"select"]) {
                    
                    if (profile.select_content_index >= 0) {
                        
                        [params setObject:@(profile.select_content_index) forKey:profile.param_key];
                    }
                }
                else if ([profile.type isEqualToString:@"select_location"]) {
                    
                    if (self.cityCode.length > 0) {
                        
                        [params setObject:self.cityCode forKey:profile.param_key];
                        [params setValue:self.cityID forKey:@"local"];
                    }
                    else {
                        
                        [params setObject:self.cityID forKey:profile.param_key];
                    }
                }
                else if ([profile.type isEqualToString:@"input"]) {
                    
                    if (profile.value.length > 0) {
                        
                        [params setObject:profile.value forKey:profile.param_key];
                    }
                }
            }
        }
    }
    
    [self.params removeAllObjects];
    self.params = params;
    
    return YES;
}

- (void)submitAction {
    
    [self.view endEditing:YES];
    
    // 入资状态判断（0未实名，1已实名，2留资1完成，3留资2完成）
    [self.params setObject:@"2" forKey:@"status"];
    
    // 埋点
    [FPRecordPointModel recordPointWithType:@"1" success:^(NSInteger code, NSString * _Nonnull message) {
    } failure:^(NSError * _Nonnull error) {
    }];
    NSLog(@"入参是：%@",self.params);
    [FPUserInfoModel updateAdvertUserInfoWithParam:self.params success:^(NSString * _Nonnull msg, NSInteger code) {
        
        if (code == 200) {
            
//            [self showText:@"提交成功"];
            // 资料审核 提交成功之后
//            FPNoDataController *vc = [[FPNoDataController alloc] init];
//            vc.type = RecordListTypeInReview;
//            [self.navigationController pushViewController:vc animated:YES];
            FPMeProfileTwoController *vc = [[FPMeProfileTwoController alloc] init];
            [self.navigationController pushViewController:vc animated:YES];
            
            [[NSNotificationCenter defaultCenter] postNotificationName:LoginSuccessNotification object:nil];
            
//            [FPUserInfoModel getUserInfoWithSuccess:^(FPUserInfoModel * _Nonnull model) {
//                // 获取一下用户信息
//            } failure:^(NSError * _Nonnull error) {
//            }];
        }
        else {
            
            [self showText:msg];
        }
        
    } failure:^(NSError * _Nonnull error) {
        
    }];
}
@end
